<template>
    <div>
      <el-dialog v-model="dialog.isdialog">
        <el-card>
          <h3>{{ dialog.title }}</h3>
          <p>{{ dialog.content }}</p>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialog.isdialog = false">取 消</el-button>
            <el-button type="primary" @click="dialog.isdialog = false">确 定</el-button>
          </div>
        </el-card>
      </el-dialog>
    </div>
  
    <el-container>
      <el-header>编辑章节</el-header>
      <el-main>
        <el-form :model="post" ref="postForm" @submit.native.prevent="submitPost" enctype="multipart/form-data">
          <el-form-item label="标题" prop="title">
            <el-input v-model="post.title"></el-input>
          </el-form-item>
  
          <el-upload
            action="/api/upload/file1"
            :on-success="handleUploadSuccess"
            :before-upload="beforeImageUpload"
            :auto-upload="true"
            class="upload-demo"
          >
            <el-button slot="trigger">插图上传</el-button>
            <template #tip>仅支持jpg/png格式，大小不超过2MB。</template>
          </el-upload>
  
          <el-form-item label="内容" prop="content">
            <el-input
              type="textarea"
              :rows="20"
              resize="both"
              v-model="post.content"
              @input="updateMarkdownPreview"
            ></el-input>
          </el-form-item>
  
          <!-- 上传封面图片 -->
          <el-form-item>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="post.coverImage" :src="post.coverImage" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon">封面</i>
            </el-upload>
          </el-form-item>
  
          <el-form-item>
            <el-button type="primary" native-type="submit">提交</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  
    <el-container>
      <el-header>MD效果：</el-header>
      <el-main>
        <h3>{{ post.title }}</h3>
        <div id="markdownPreview" v-html="convertToHtml(post.content)"></div>
      </el-main>
    </el-container>
  </template>
  
  <script setup lang="ts">
  import MarkdownIt from 'markdown-it';
  import { ElMessage } from 'element-plus';
  import { ref, onMounted } from 'vue';
  import { useUserStore } from '@/stores/user';
  import axios from 'axios';
  import { useRouter, useRoute } from 'vue-router';

  
  const router = useRouter();
  const route = useRoute();
  const md = new MarkdownIt();
  
  // 获取URL中的章节ID
  const chapterId = ref(route.params.id);
  
  // 获取用户登录状态
  const user = useUserStore();
  const my_id = user.loginstatus ? user.userInfo.id : -1;
  
  // 表单数据
  const post = ref({
    title: '',
    content: '',
    coverImage: '',

  });
  // Dialog 用于显示提示信息
  const dialog = ref({
    title: '',
    content: '',
    isdialog: false
  });
  
  // 页面加载时获取章节数据
  onMounted(() => {
    if (chapterId.value) {
      fetchChapterData();
    }
  });
  
  // 获取章节数据
  function fetchChapterData() {
    axios.get(`/api/chapters/${chapterId.value}`).then((res) => {
      console.log(res);
      
      const data = res.data.data;
      
      post.value = data;

    }).catch((err) => {
      dialog.value.title = '提示';
      dialog.value.content = '章节数据加载失败';
      dialog.value.isdialog = true;
    });
  }
  
  // 提交表单，更新章节
  function submitPost() {

  
    axios.put(`/api/chapters/${chapterId.value}`, post.value)
      .then(res => {
        console.log(res);
        if (res.data.code !== 200) {
          dialog.value.title = '提示';
          dialog.value.content = '更新失败';
          dialog.value.isdialog = true;
          return;
        }
        dialog.value.title = '提示';
        dialog.value.content = '更新成功';
        dialog.value.isdialog = true;
        router.push(`/chapter_read/${chapterId.value}`);
      })
      .catch(() => {
        dialog.value.title = '提示';
        dialog.value.content = '更新失败';
        dialog.value.isdialog = true;
      });
  }
  
  // 处理图片上传成功的回调
  function handleUploadSuccess(response: any) {
    if (response && response.path) {
      post.value.coverImage = response.path;
    } else {
      ElMessage.error('图片上传成功，但未返回预期的URL');
    }
  }
  
  // 上传图片前的校验
  function beforeImageUpload(rawFile: File) {
    return rawFile.size / 1024 / 1024 < 4;  // 限制大小为4MB
  }
  
  // Markdown转换为HTML
  function convertToHtml(content: string) {
    return md.render(content);
  }
  
  function updateMarkdownPreview() {
    // 预览更新逻辑
  }
  </script>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 100px;
    height: 100px;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  </style>
  